package org.droid.campus.api.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.droid.campus.common.ActionHandler;
import org.droid.campus.common.RequestTypeException;
import org.droid.campus.common.Enums.ActionStatus;
import org.droid.campus.util.RespStatusBuilder;

/**
 * Servlet implementation class DevClientServlet
 * @category updated at 2011-08-11 , added GZIP support
 */

public class DevClientServlet extends HttpServlet  {
	private static final long serialVersionUID = 1L;
    private final static Logger log = Logger.getLogger(DevClientServlet.class) ;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DevClientServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy() ;
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub		
		request.setCharacterEncoding("UTF-8") ;
		
		StringBuffer respData = null ;
		ActionHandler action = null ;
		try {
			action = ParameterValidatorFilter.routeRequestAction(request) ;
			
			respData = action.Do(request, response) ;
		} catch (RequestTypeException e) {
			// TODO Auto-generated catch block
			log.error("RequestType Error : " , e) ;
			respData = RespStatusBuilder.message(ActionStatus.REQUEST_TYPE_ERROR) ;
		} finally {
			
				action = null;
		}
		
		PrintWriter pw = null ;
		
		String isGzipRequired = request.getParameter("gzip") ;
		
		if(isGzipRequired != null && isGzipRequired.equals("1")){
			//need return gzip data
			response.setHeader("Content-Encoding", "gzip"); 
			pw = new PrintWriter(new GZIPOutputStream(response.getOutputStream()));
		} else {
			//common
			response.setCharacterEncoding("UTF-8") ;
			response.setContentType("text/xml") ;
			pw = response.getWriter() ;
		}
		
		pw.print(respData) ;
		pw.flush() ;
		pw.close() ;
		return ;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
